import { Component, OnInit, NgZone, ViewChild, ElementRef, OnDestroy, Inject } from '@angular/core';
import { MSLayoutComponent, BrandService } from '@brand';
import { _HttpClient, TitleService, SettingsService } from '@delon/theme';
import { NzNotificationService, NzDrawerService } from 'ng-zorro-antd';
import { of, zip, Observable, fromEvent, Subject } from 'rxjs';
import { catchError, takeUntil } from 'rxjs/operators';
import { DOCUMENT } from '@angular/common';
import { STComponent, STColumn, STRequestOptions, STColumnTag, STColumnBadge, STData } from '@delon/abc';
import { applyCC } from '@shared';
import { HttpParams, HttpHeaders, HttpResponse } from '@angular/common/http';
import { Router } from '@angular/router';
import { RouteService } from '@core';
import { GALLERY_CONF } from 'ngx-image-gallery';
import { saveAs } from 'file-saver';

const BADGE_SALE: STColumnBadge = {
  '1': { text: '有售', color: 'success' },
  '0': { text: '下架', color: 'error' },
};

/**
 * 商品列表
 */
@Component({
  selector: 'app-product-list',
  templateUrl: './product-list.component.html',
  styleUrls: ['./product-list.component.less'],
})
export class ProductListComponent implements OnInit, OnDestroy {
  conf: GALLERY_CONF = {
    imageOffset: '0px',
    showDeleteControl: false,
  };
  images = [];
  mode = 'grid';
  brands = [];
  brandTypes = [];
  years = [];
  useGroups = [];
  sales = ['批发', '电商', '零售', '国贸'];
  expandMode = true; // true-展开 false-折叠
  host = `${window.location.origin + window.location.pathname}`;
  btns = [{ remark: '下载搜索结果', icon: 'icon-download', loading: false }];
  prodinfo_export_btn = false;
  loading = false;
  hasMore = false;
  total = 0;
  data = [];
  url = `/cf/prod/sys-prod/page`;
  @ViewChild('st', { static: false }) st: STComponent;
  @ViewChild('gallery', { static: false }) gallery: any;
  columns: STColumn[] = applyCC([
    { title: '图片', type: 'img', render: 'img' },
    { title: 'SKU', index: 'productCd' },
    { title: 'SAP代码', index: 'sap', ccChecked: false },
    { title: '品牌', index: 'brand' },
    { title: '分类', index: 'brandType' },
    { title: '款号', index: 'style' },
    { title: '色号', index: 'colorCd' },
    { title: '年份', index: 'year' },
    { title: '款式', index: 'useGroup' },
    { title: '批发销售', index: 'zpfxs', type: 'badge', badge: BADGE_SALE },
    { title: '电商销售', index: 'zdsxs', type: 'badge', badge: BADGE_SALE },
    { title: '零售销售', index: 'zlsxs', type: 'badge', badge: BADGE_SALE },
    { title: '国贸销售', index: 'zgmxs', type: 'badge', badge: BADGE_SALE },
    {
      title: '操作',
      buttons: [
        {
          text: '详情',
          type: 'link',
          click: (record: STData, modal?: any, instance?: STComponent) => {
            if (this.mode === 'list') {
              this.q.pi = this.st.pi;
            }
            this.router.navigateByUrl(`/prod/list/view/${record.productCd}`, {
              state: { pi: this.st.pi, q: this.q },
            });
          },
        },
      ],
    },
  ]);

  q: any = {
    pi: 1,
    ps: 20,
    keyword: null,
    brands: [],
    brandTypes: [],
    years: [],
    useGroups: [],
    sales: [],
    sort: '',
  };
  // 显示、隐藏抽屉
  s1 = [];
  s2 = [];
  s3 = [];
  s4 = [];
  s5 = [];

  visible = false;
  placement = 'right';
  sumSelect = 0;

  open(): void {
    this.s1 = this.q.brands;
    this.s2 = this.q.brandTypes;
    this.s3 = this.q.years;
    this.s4 = this.q.useGroups;
    this.s5 = this.q.sales;
    this.visible = true;
  }

  // 取消筛选项
  close(): void {
    this.visible = false;
  }

  // 确定使用筛选项
  sureSelect() {
    this.q.brands = this.s1;
    this.q.brandTypes = this.s2;
    this.q.years = this.s3;
    this.q.useGroups = this.s4;
    this.q.sales = this.s5;

    this.refreshSum();
    this.visible = false;
    this.toGetData(1);
  }

  refreshSum() {
    this.sumSelect = 0;
    this.sumSelect =
      this.q.sales.length +
      this.q.brands.length +
      this.q.brandTypes.length +
      this.q.years.length +
      this.q.useGroups.length;
  }

  brandChange(checked: boolean, tag: string): void {
    if (checked) {
      this.s1.push(tag);
    } else {
      this.s1 = this.s1.filter(t => t !== tag);
    }
  }
  brandTypeChange(checked: boolean, tag: string): void {
    if (checked) {
      this.s2.push(tag);
    } else {
      this.s2 = this.s2.filter(t => t !== tag);
    }
  }
  yearChange(checked: boolean, tag: string): void {
    if (checked) {
      this.s3.push(tag);
    } else {
      this.s3 = this.s3.filter(t => t !== tag);
    }
  }
  useGroupChange(checked: boolean, tag: string): void {
    if (checked) {
      this.s4.push(tag);
    } else {
      this.s4 = this.s4.filter(t => t !== tag);
    }
  }
  salesChange(checked: boolean, tag: string): void {
    if (checked) {
      this.s5.push(tag);
    } else {
      this.s5 = this.s5.filter(t => t !== tag);
    }
  }

  // 显示、隐藏抽屉

  constructor(
    public http: _HttpClient,
    private notice: NzNotificationService,
    private srv: BrandService,
    titSrv: TitleService,
    private ngZone: NgZone,
    private router: Router,
    private routeStateSrv: RouteService,
    private settings: SettingsService,
  ) {
    titSrv.setTitleByI18n('product.title.doc');
    const stmode = localStorage.getItem('prodmode');
    if (stmode) {
      this.mode = stmode;
    }
    const tm = localStorage.getItem('expandMode');
    if (this.mode === 'grid') {
      if (tm === '1') {
        this.expandMode = true;
      } else if (tm === '2') {
        this.expandMode = false;
      } else {
        this.expandMode = true;
      }
    }

    const tq = this.routeStateSrv.get('q');
    if (tq) {
      this.q = tq;
      this.refreshSum();
    }
  }

  ngOnInit() {
    this.prodinfo_export_btn = this.settings.user.permissions.prodinfo_export_btn;
    this.loadFilters();
    if (this.mode === 'grid') {
      const tq = this.routeStateSrv.get('q');
      this.toGetData(tq ? tq.pi : 1);
    }
  }

  ngOnDestroy(): void {}

  toSearch(e) {
    this.q.keyword = e;
    this.toGetData(1);
  }

  get isMobile() {
    return this.srv.isMobile;
  }

  /**
   * 表格类型的请求预处理
   */
  preHandle = (opt: STRequestOptions): STRequestOptions => {
    const params = this.returnParam();
    opt.params = { ...opt.params, ...params };
    return opt;
  };
  /**
   * 表格数据返回预处理
   */
  resPreHandle = (data: STData[], rawData?: any): STData[] => {
    this.images = [];
    this.images = data.map(p => {
      return {
        url: p.pic
          ? `${window.location.origin + window.location.pathname}/cf/admin/sysfile/f/${p.pic}`
          : './assets/img/noimg.png',
        title: p.productCd,
      };
    });
    return data;
  };

  returnParam(): { [key: string]: any } {
    const brands = this.q.brands.join(',');
    const years = this.q.years.join(',');
    const useGroups = this.q.useGroups.join(',');
    const brandTypes = this.q.brandTypes.join(',');
    const zpfxs = this.q.sales.indexOf('批发') > -1 ? '1' : '';
    const zdsxs = this.q.sales.indexOf('电商') > -1 ? '1' : '';
    const zlsxs = this.q.sales.indexOf('零售') > -1 ? '1' : '';
    const zgmxs = this.q.sales.indexOf('国贸') > -1 ? '1' : '';
    return {
      keyword: this.q.keyword || '',
      sort: this.q.sort || '',
      xsstatus: this.q.sales.length > 0 ? '1' : '',
      zpfxs,
      zdsxs,
      zlsxs,
      zgmxs,
      brands,
      years,
      useGroups,
      brandTypes,
    };
  }

  /**
   * 排序数据
   */
  sort(type) {
    this.q.sort = type;
    this.toGetData(1);
  }

  toGetData(pi) {
    if (this.mode === 'grid') {
      this.getData(pi);
    } else {
      this.st.reset(pi);
    }
  }

  /**
   * 获取分页数据
   * @param pi 页码
   */
  getData(pi = 1) {
    this.loading = true;
    const params = this.returnParam();
    this.q.pi = pi;
    params.current = this.q.pi;
    params.size = this.q.ps;
    this.http
      .get(`${this.expandMode ? '/cf/prod/sys-prod/page' : '/cf/prod/sys-prod/pageStyle'}`, params)
      .pipe(catchError(err => of(err)))
      .subscribe(res => {
        this.loading = false;
        if (res.status === 200) {
          this.data = [];
          this.images = [];
          this.data = [...res.data.records];
          if (this.expandMode) {
            this.images = this.data.map(p => {
              return {
                url: p.pic
                  ? `${window.location.origin + window.location.pathname}/cf/admin/sysfile/f/${p.pic}`
                  : './assets/img/noimg.png',
                title: p.productCd,
              };
            });
          }
          this.total = res.data.total;
          this.hasMore = res.data.total > res.data.current && res.data.records.length === this.q.ps;
        }
      });
  }

  /**
   * 加载搜索字典
   */
  loadFilters() {
    const api = [
      this.http.get(`/cf/prod/sys-prod/brands`),
      this.http.get(`/cf/prod/sys-prod/years`),
      this.http.get(`/cf/prod/sys-prod/useGroups`),
    ];
    zip(...api)
      .pipe(
        catchError(([brands, years, useGroups]) => {
          return [brands, years, useGroups];
        }),
      )
      .subscribe(([brands, years, useGroups]) => {
        this.brands = brands.data;
        this.years = years.data;
        this.useGroups = useGroups.data;
      });
  }

  toList() {
    this.q.qi = 1;
    this.mode = 'list';
    this.st.reset(1);
    localStorage.setItem('prodmode', 'list');
  }

  toGrid() {
    this.mode = 'grid';
    localStorage.setItem('prodmode', 'grid');
    this.toGetData(1);
  }

  goView(p, idx) {
    const { expandMode } = this;
    this.router.navigateByUrl(`/prod/list/view/${expandMode ? p.productCd : p.prods[idx].productCd}`, {
      state: { pi: this.st.pi, q: this.q, expandMode: expandMode ? 1 : 2 },
    });
  }

  showGallery(idx) {
    this.gallery.open(idx);
  }

  showGallery2(p, idx, innerIndex) {
    if (this.mode === 'grid' && !this.expandMode) {
      this.images.concat([]);
      const tmpNewImgs = p.prods.map(tp => {
        return {
          url: tp.pic
            ? `${window.location.origin + window.location.pathname}/cf/admin/sysfile/f/${tp.pic}`
            : './assets/img/noimg.png',
          title: tp.productCd,
        };
      });
      this.images = this.images.concat(tmpNewImgs);
    }
    setTimeout(() => {
      this.showGallery(this.expandMode ? idx : innerIndex);
    }, 200);
  }

  /**
   * 折叠或展开sku
   */
  switchFold(event) {
    this.expandMode = event;
    localStorage.setItem('expandMode', event ? '1' : '2');
    this.toGetData(1);
  }

  downloadFile(idx) {
    this.btns[idx].loading = true;
    const params = this.returnParam();
    const head = new HttpHeaders({
      'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
    });
    this.http
      .request('get', `/cf/prod/sys-prod/export/batch?`, {
        headers: head,
        responseType: 'blob',
        observe: 'response',
        params,
      })
      .subscribe((res: HttpResponse<Blob>) => {
        this.btns[idx].loading = false;
        const filename = `产品资料.xlsx`;
        saveAs(res.body, decodeURI(filename));
      });
  }
}
